package com.yc.sakuralxm.uestcscanning.carnum

import android.app.Activity
import android.content.Context
import android.inputmethodservice.Keyboard
import android.inputmethodservice.KeyboardView
import android.inputmethodservice.KeyboardView.OnKeyboardActionListener
import android.text.Editable
import android.text.InputType
import android.view.View
import android.view.WindowManager
import android.view.animation.Animation
import android.view.animation.AnimationUtils
import android.view.inputmethod.InputMethodManager
import android.widget.EditText

import com.yc.sakuralxm.uestcscanning.R
import com.yc.sakuralxm.uestcscanning.tools.L

import java.lang.reflect.InvocationTargetException
import java.lang.reflect.Method
import java.util.ArrayList
import java.util.logging.Level

class CarKeyboardUtil(private val mActivity: Activity, private var mEdit: EditText?) {

    private val mContext: Context
    private val mKeyboardView: KeyboardView

    /**
     *
     * 省份简称键盘
     */
    private val province_keyboard: Keyboard
    /**
     * 数字与大写字母键盘
     */
    private val number_keyboar: Keyboard

    /**
     * 软键盘切换判断
     */
    private var isChange = true
    /**
     * 判定是否是中文的正则表达式 [\\u4e00-\\u9fa5]判断一个中文 [\\u4e00-\\u9fa5]+多个中文
     */
    private val reg = "[\\u4e00-\\u9fa5]"

    /**
     * 软键盘展示状态
     */
    val isShow: Boolean
        get() = mKeyboardView.visibility == View.VISIBLE


    private var openAnimation: Animation? = null
    private var closeAnimation: Animation? = null

    fun getmEdit(): EditText? {
        return mEdit
    }

    fun setmEdit(mEdit: EditText) {
        this.mEdit = mEdit
    }

    init {
        mContext = mActivity
        init()
        province_keyboard = Keyboard(mContext, R.xml.province_abbreviation)
        number_keyboar = Keyboard(mContext, R.xml.number_or_letters)
        mKeyboardView = mActivity
                .findViewById(R.id.keyboard_view) as KeyboardView
        mKeyboardView.keyboard = province_keyboard
        mKeyboardView.isEnabled = true
        mKeyboardView.isPreviewEnabled = false
        val listener = object : OnKeyboardActionListener {
            override fun swipeUp() {}

            override fun swipeRight() {}

            override fun swipeLeft() {}

            override fun swipeDown() {}

            override fun onText(text: CharSequence) {}

            override fun onRelease(primaryCode: Int) {}

            override fun onPress(primaryCode: Int) {}

            override fun onKey(primaryCode: Int, keyCodes: IntArray) {
                val editable = mEdit!!.text
                val start = mEdit!!.selectionStart
                if (primaryCode == -1) {// 省份简称与数字键盘切换
                    changeKeyboard()
                } else if (primaryCode == -3) {// 回退
                    if (editable != null && editable.length > 0) {
                        //没有输入内容时软键盘重置为省份简称软键盘
                        if (editable.length == 1) {
                            changeKeyboard(false)
                        }
                        if (start > 0) {
                            editable.delete(start - 1, start)
                        }
                    }
                } else {
                    editable!!.insert(start, Character.toString(primaryCode.toChar()))
                    // 判断第一个字符是否是中文,是，则自动切换到数字软键盘
                    if (mEdit!!.text.toString().matches(reg.toRegex())) {
                        changeKeyboard(true)
                    }
                }
            }
        }
        mKeyboardView.setOnKeyboardActionListener(listener)
    }


    /**
     * 按切换键时切换软键盘
     */
    fun changeKeyboard() {
        if (isChange) {
            mKeyboardView.keyboard = number_keyboar
        } else {
            mKeyboardView.keyboard = province_keyboard
        }
        isChange = !isChange
    }

    /**
     * 指定切换软键盘 isnumber false表示要切换为省份简称软键盘 true表示要切换为数字软键盘
     */
    fun changeKeyboard(isnumber: Boolean) {
        if (isnumber) {
            mKeyboardView.keyboard = number_keyboar
        } else {
            mKeyboardView.keyboard = province_keyboard
        }
        isChange = !isChange
    }

    /**
     * 软键盘展示
     */
    fun showKeyboard() {
        L.e(" 调用了显示")
        mKeyboardView.visibility = View.VISIBLE
        startAnimation()
    }

    /**
     * 软键盘隐藏
     */
    fun hideKeyboard() {
        stopAnimation()
        mKeyboardView.visibility = View.GONE
    }

    /**
     * 禁掉系统软键盘
     */
    fun hideSoftInputMethod() {
        mActivity.window.setSoftInputMode(
                WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN)
        val currentVersion = android.os.Build.VERSION.SDK_INT
        var methodName: String? = null
        if (currentVersion >= 16) {
            // 4.2
            methodName = "setShowSoftInputOnFocus"
        } else if (currentVersion >= 14) {
            // 4.0
            methodName = "setSoftInputShownOnFocus"
        }
        if (methodName == null) {
            mEdit!!.inputType = InputType.TYPE_NULL
        } else {
            val cls = EditText::class.java
            val setShowSoftInputOnFocus: Method
            try {
                setShowSoftInputOnFocus = cls.getMethod(methodName,
                        Boolean::class.javaPrimitiveType)
                setShowSoftInputOnFocus.isAccessible = true
                setShowSoftInputOnFocus.invoke(mEdit, false)
            } catch (e: NoSuchMethodException) {
                mEdit!!.inputType = InputType.TYPE_NULL
                e.printStackTrace()
            } catch (e: IllegalAccessException) {
                e.printStackTrace()
            } catch (e: IllegalArgumentException) {
                e.printStackTrace()
            } catch (e: InvocationTargetException) {
                e.printStackTrace()
            }

        }
    }

    /**
     * 隐藏系统软键盘
     */
    fun hideSystemKeyBroad() {
        (mActivity.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager).hideSoftInputFromWindow(mActivity.currentFocus!!.windowToken, InputMethodManager.HIDE_NOT_ALWAYS)

    }

    private fun init() {
        openAnimation = AnimationUtils.loadAnimation(mActivity, R.anim.anim_entry_from_bottom)
        closeAnimation = AnimationUtils.loadAnimation(mActivity, R.anim.anim_leave_from_bottom)
        closeAnimation!!.setAnimationListener(object : Animation.AnimationListener {
            override fun onAnimationStart(arg0: Animation) {

            }

            override fun onAnimationRepeat(arg0: Animation) {

            }

            override fun onAnimationEnd(arg0: Animation) {

            }
        })
    }

    private fun startAnimation() {
        if (openAnimation != null) {
            mKeyboardView.startAnimation(openAnimation)
        }
    }

    fun stopAnimation() {
        if (closeAnimation != null) {
            mKeyboardView.startAnimation(closeAnimation)
        }
    }

}
